﻿#include "robotsettingwid.h"
#include <QMessageBox.h>
#include "ui_robotsettingwid.h"
#include "cfgjsonrw.h"

RobotSettingWid::RobotSettingWid(QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::RobotSettingWid())
{
	ui->setupUi(this);
	setStyleSheet("font: 12pt \"Agency FB\"");
	m_base = new PositionSettingWid(this);
	QHBoxLayout* lay = new QHBoxLayout;
	lay->addWidget(m_base);
	ui->groupBox_2->setLayout(lay);
}

RobotSettingWid::~RobotSettingWid()
{
	delete ui;
}

std::map<QString, QString> g_typeMapping = {
	{ "测试专用", "TEST"},
	{ "ABB", "ABB"},
	{ "KUKA", "KUKA"},
	{ "埃斯顿", "ESTUN"},
	{ "法兰克", "FANUC"}
};

QString RobotSettingWid::GetRobotType(const QString& index)
{
	if (g_typeMapping.find(index) != g_typeMapping.end()) {
		return g_typeMapping[index];
	}
	return "TEST";
}

QString RobotSettingWid::GetRobotTypeString(const QString& type)
{
	for (auto& iter : g_typeMapping) {
		if (iter.second == type) {
			return iter.first;
		}
	 }
	return "测试专用";
}


void RobotSettingWid::Init()
{
	QStringList types;
	for (auto& iter : g_typeMapping) {
		types.append(iter.first);
	}
	ui->comboBox->addItems(types);
	auto cfg = cfgrw->GetRobotCfg();
	ui->lineEdit->setText(cfg.id());
	ui->comboBox->setCurrentText(GetRobotTypeString(cfg.brand()));
	ui->IP->setText(cfg.ip());
	ui->statePort->setValue(cfg.statePort());
	ui->cmdPort->setValue(cfg.cmdPort());
	m_base->Init(cfg.origin());
	
	// 夹具初始
	auto jig = cfgrw->GetJigCfg();
	ui->spinBox->setValue(jig.id());
	ui->comboBox_2->setCurrentIndex(jig.type());
	ui->spinBox_2->setValue(jig.size().length());
	ui->spinBox_3->setValue(jig.size().width());
	ui->spinBox_4->setValue(jig.rob().x());
	ui->spinBox_10->setValue(jig.rob().y());
	ui->spinBox_11->setValue(jig.rob().z());
	ui->spinBox_12->setValue(jig.rob().a());
	ui->spinBox_13->setValue(jig.rob().b());
	ui->spinBox_14->setValue(jig.rob().c());

}

//void RobotSettingWid::on_comboBox_currentIndexChanged(const QString& index)
//{
//	//QString type = GetRobotType(index);
//
//}

/*保存*/
void RobotSettingWid::on_pushButton_clicked()
{
	RobotJ cfg = {};
	cfg.id = ui->lineEdit->text();
	cfg.brand = GetRobotType(ui->comboBox->currentText());
	cfg.ip = ui->IP->text();
	cfg.statePort = ui->statePort->value();
	cfg.cmdPort = ui->cmdPort->value();
	cfg.origin = m_base->GetPositon();

	if (!cfgrw->UpdateRobotCfg(cfg)) {
		QMessageBox::warning(this, "ERROR", "保存失败");
	}

	// 夹具保存
	JigCfg jig = {};
	jig.id() = ui->spinBox->value();
	jig.type() = ui->comboBox_2->currentIndex();
	jig.size().length() = ui->spinBox_2->value();
	jig.size().width() = ui->spinBox_3->value();
	jig.rob().x = (ui->spinBox_4->value());
	jig.rob().y() = ui->spinBox_10->value();
	jig.rob().z() = ui->spinBox_11->value();
	jig.rob().a() = ui->spinBox_12->value();
	jig.rob().b() = ui->spinBox_13->value();
	jig.rob().c() = ui->spinBox_14->value();
	if (!cfgrw->SetJigCfg(jig)) {
		QMessageBox::warning(this, "ERROR", "夹具信息保存失败");
	}

}

